package com.trepadora.mapper;

import java.io.IOException;
import java.util.Date;

import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.View;
import com.fourspaces.couchdb.ViewResults;

/**
 * 
 * @author Karol Lotkowski
 * 
 */
public class ChatMapper extends CouchDBMainMapper {

	/**
	 * 
	 * Save chat in DB
	 * 
	 * @param room
	 * @param who
	 * @param post
	 * @throws IOException
	 * 
	 * @return document id
	 */
	public String saveChat(final String room, final String who, final String post) throws IOException {

		Date now = new Date();
		Document chatDoc = new Document();
		
		chatDoc.put("type", "chat");
		chatDoc.put("room", room);
		chatDoc.put("who", who);
		chatDoc.put("post", post);
		chatDoc.put("date", now.getTime());
		
		db.saveDocument(chatDoc);
		
		return chatDoc.getId();
	}
	
	/**
	 * Get all chats from selected room
	 * 
	 * @param roomId
	 * @return ViewResults
	 */
	public ViewResults getAllChatsByRoomId(final String roomId){
		
		View allChatsByRoom = new View(buildViewDoc("chat", "byRoom"));
		allChatsByRoom.setKeyString(roomId);
	
		ViewResults result = db.view(allChatsByRoom);
		
		return result;
	}
}
